package com.wyix;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;

/**
 * @author wangdx
 * @since 2025/8/5
 */
public class HttpClientAsyncExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(5))
                .build();

        // 创建POST请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString("name=John&age=30"))
                .build();

        // 异步发送请求（非阻塞）
        CompletableFuture<HttpResponse<String>> future = client.sendAsync(
                request,
                HttpResponse.BodyHandlers.ofString()
        );
        System.out.println("处理其他任务。。。。");

        // 处理异步结果
        future.thenAccept(response -> {
            System.out.println("异步响应状态码: " + response.statusCode());
            System.out.println("异步响应体: " + response.body());
        }).join(); // 等待异步完成
        System.out.println("异步请求完成");
    }
}
